package com.mobartisan.vehiclenetstore.getui_push;

import android.content.Context;
import android.os.Message;
import android.util.Log;


import com.google.gson.Gson;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.mobartisan.vehiclenetstore.ECarApplication;
import com.mobartisan.vehiclenetstore.bean.NotificationBeen;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by L on 2017/5/10.
 */

public class IntentPushRemindService extends GTIntentService {

    private static final String TAG = IntentPushRemindService.class.getSimpleName();

    /**
     * 为了观察透传数据变化.
     */
    @Override
    public void onReceiveServicePid(Context context, int i) {

    }

    @Override
    public void onReceiveClientId(Context context, String s) {

    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        String appid = msg.getAppid();
        String taskid = msg.getTaskId();
        String messageid = msg.getMessageId();
        byte[] payload = msg.getPayload();
        String pkg = msg.getPkgName();
        String cid = msg.getClientId();

        // 第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
        boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
        Log.d(TAG, "call sendFeedbackMessage = " + (result ? "success" : "failed"));

        Log.d(TAG, "onReceiveMessageData -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nmessageid = " + messageid + "\npkg = " + pkg
                + "\ncid = " + cid);

        if (payload == null) {
            Log.e(TAG, "receiver payload = null");
        } else {
            String data = new String(payload);

            Log.e(TAG, "data----------------"+data);
            sendMessage(data, 0);
            if (isJson(data)){
                Gson gson = new Gson();
                NotificationBeen notificationBeen = gson.fromJson(data, NotificationBeen.class);
                data = notificationBeen.getBody();
                sendMessage(data, 0);
            }

        }

        Log.d(TAG, "----------------------------------------------------------------------------------------------");
    }

    /**
     * 判断字符串是不是json格式的字符串
     * @param value
     * @return
     */
    public static boolean isJson(String value) {
        try {
            new JSONObject(value);
        } catch (JSONException e) {
            return false;
        }
        return true;
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean b) {

    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage gtCmdMessage) {

    }

    private void sendMessage(String data, int what) {
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = data;
        ECarApplication.sendMessage(msg);
    }
}
